package com.hulman.oms.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.ShifterReport;
import com.hulman.oms.bean.User;
import com.hulman.oms.bean.WeatherInfo;
import com.hulman.oms.dao.ShifterReportDao;
import com.hulman.oms.util.DateUtil;
import com.hulman.oms.util.StringUtil;
import com.hulman.oms.util.SubjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @Author: maxwellens
 */
@Service
public class ShifterReportService
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private ShifterReportDao shifterReportDao;
    @Autowired
    private WeatherService weatherService;
    @Autowired
    private PatrolService patrolService;
    @Autowired
    private FaultService faultService;
    @Autowired
    private RepairService repairService;
    @Autowired
    private WorkTaskService workTaskService;
    @Autowired
    private OnlyOfficeService onlyOfficeService;

    public List<ShifterReport> findShifterReports(Map<String, Object> map)
    {
        return shifterReportDao.findShifterReports(map);
    }

    public Integer findShifterReportsCount(Map<String, Object> map)
    {
        return shifterReportDao.findShifterReportsCount(map);
    }

    public Result findShifterReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = shifterReportDao.findShifterReportsCount(map);
        List<ShifterReport> data = shifterReportDao.findShifterReports(map);
        return new Result(data, count);
    }

    public ShifterReport findShifterReportById(Integer id)
    {
        return shifterReportDao.findShifterReportById(id);
    }

    public void saveShifterReport(ShifterReport shifterReport)
    {
        if (shifterReport.getId() != null && shifterReport.getId() != 0)
        {
            shifterReportDao.updateShifterReport(shifterReport);
        } else
        {
            shifterReportDao.insertShifterReport(shifterReport);
        }
    }

    public void deleteShifterReportById(Integer id)
    {
        shifterReportDao.deleteShifterReportById(id);
    }

    public void deleteShifterReports(int[] ids)
    {
        shifterReportDao.deleteShifterReports(ids);
    }

    public ShifterReport createTodayShifterReport()
    {
        ShifterReport shifterReport = new ShifterReport();
        shifterReport.setReportDate(new Date());
        shifterReport.setState(0);
        WeatherInfo weatherInfo = weatherService.getWeatherInfo();
        shifterReport.setWeather(weatherInfo.getWeather());
        shifterReportDao.insertShifterReport(shifterReport);
        return shifterReport;
    }

    /**
     * 生成报表
     *
     * @param shifterReport
     * @throws IOException
     */
    public void generate(ShifterReport shifterReport) throws IOException
    {
        User user = SubjectUtil.getUser();
        shifterReport.setShifterId(user.getId());
        shifterReport.setShifterName(user.getName());
        shifterReport.setState(1);
        Map<String, Object> head = new HashMap<>();
        head.put("weather", shifterReport.getWeather());
        head.put("content", shifterReport.getContent());
        head.put("coordination", shifterReport.getCoordination());
        head.put("matter", shifterReport.getMatter());
        head.put("shifterName", shifterReport.getShifterName());
        head.put("reportDate", DateUtil.toChineseDate(shifterReport.getReportDate()));
        //生成报表
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/shifter-report.xlsx");
        String fileId = StringUtil.uuid() + ".xlsx";
        Path filePath = Paths.get(fileHome, fileId);
        OutputStream outputStream = Files.newOutputStream(filePath);
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(head, writeSheet);
        excelWriter.finish();
        shifterReport.setFileId(fileId);
        shifterReportDao.updateShifterReport(shifterReport);
        onlyOfficeService.create(fileId, DateUtil.toChineseDate(shifterReport.getReportDate()) + "值班长日报.xlsx");
    }

    /**
     * 提交报表
     *
     * @param shifterReport
     * @throws IOException
     */
    public void submit(ShifterReport shifterReport) throws IOException
    {
        User user = SubjectUtil.getUser();
        shifterReport.setShifterId(user.getId());
        shifterReport.setShifterName(user.getName());
        shifterReport.setState(2);
        shifterReport.setSubmitTime(new Date());
        shifterReportDao.updateShifterReport(shifterReport);
    }

    public String getWorkContents(Date date)
    {
        StringBuilder sb = new StringBuilder();
        String patrolContents = patrolService.getPatrolContents(date);
        String faultContents = faultService.getFaultContents(date);
        String repairContents = repairService.getRepairContents(date);
        String workTaskContents = workTaskService.getWorkTaskContents(date);
        if (!StringUtil.isEmpty(patrolContents))
        {
            sb.append("巡检工作：\n");
            sb.append(patrolContents);
        }
        if (!StringUtil.isEmpty(faultContents))
        {
            sb.append("发现缺陷：\n");
            sb.append(faultContents);
        }
        if (!StringUtil.isEmpty(repairContents))
        {
            sb.append("维修内容：\n");
            sb.append(repairContents);
        }
        if (!StringUtil.isEmpty(workTaskContents))
        {
            sb.append("任务工单：\n");
            sb.append(workTaskContents);
        }
        return sb.toString();
    }
}
